package com.rayo.accesscontrollercopy.utils;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;

import com.rayo.accesscontrollercopy.app.ActivityManager;
import com.rayo.accesscontrollercopy.app.CrashHandler;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by yanghaojie on 2017/3/10.
 */

public class FileUtils {
    public static File saveFile(byte[] data, String url) {
        return saveLocal(data, url);
    }

    public static File saveLocal(byte[] data, String name) {
        String strPath = getSDPath();
        BufferedOutputStream stream = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dirFirstFolder = new File(strPath);//方法二：通过变量文件来获取需要创建的文件夹名字
            if (!dirFirstFolder.exists()) { //如果该文件夹不存在，则进行创建
                dirFirstFolder.mkdirs();//创建文件夹
            }
            strPath +=  name;
            file = new File(strPath);
            fos = new FileOutputStream(file);
            stream = new BufferedOutputStream(fos);
            stream.write(data);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                fos.close();
                stream.close();
                return file;
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
    }

    /**
     * 获取SD卡或者内置存储空间可以保存资源的路径.
     * <em>此处未实现对存储空间是否充足进行判断</em>.
     *
     * @return 返回保存数据的路径, 有SD卡则是SD上的路径, 反之内置存储空间上的路径.
     */
    public static String getSDPath() {
        boolean hasSDCard = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (hasSDCard) {
            return Environment.getExternalStorageDirectory().toString() + "/keyHolder/";
        } else
            return "/data/data/package/";
    }

    /**
     * 删除单个文件
     *
     * @param filePath 被删除文件的文件名
     * @return 文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (file.isFile() && file.exists()) {
            return file.delete();
        }
        return false;
    }

    public static boolean deleteLocal(String strPath) {
        boolean flag = false;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        if (!strPath.endsWith(File.separator)) {
            strPath = strPath + File.separator;
        }
        File dirFile = new File(strPath);
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        File[] files = dirFile.listFiles();
        //遍历删除文件夹下的所有文件(包括子目录)
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                //删除子文件
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } else {
                //删除子目录
                flag = deleteLocal(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前空目录
        return dirFile.delete();
    }

    public static File findFile(String fileName) {
        boolean flag = false;
        //如果filePath不以文件分隔符结尾，自动添加文件分隔符
        String strPath = getSDPath() + fileName;
        if (!strPath.endsWith(File.separator)) {
            strPath = strPath + File.separator;
        }
        File dirFile = new File(strPath);
        if (!dirFile.exists()) {
            return null;
        }
        return new File(strPath);
    }

    public static boolean installApp(File file, Context context) {
        if (!file.exists()) {
            return false;
        }
        CrashHandler.getInstance().close();
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + file.toString()),
                "application/vnd.android.package-archive");// File.toString()会返回路径信息
        context.startActivity(i);
        ActivityManager.getInstance().closeAllActivity();
//        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
        return true;
    }
}
